package com.jiuyuan.config.filter;

import com.jiuyuan.entity.Menu;
import com.jiuyuan.entity.Role;
import com.jiuyuan.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @program: hrms
 * @description: 获取将访问url所需的角色
 * @author: Feng
 * @create: 2023-02-16 09:09
 **/
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    IMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    /**
     * @Description: 获取将访问url所需的角色
     * @Param:  * @param object
     * @return: java.util.Collection<org.springframework.security.access.ConfigAttribute>
     * @Author: Feng
     * @Date:2023/02/16 9:28
     */
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String url = ((FilterInvocation) object).getRequestUrl();
        List<Menu> menus =  menuService.getMenusWithRoles();
        for(Menu menu:menus){
            if(antPathMatcher.match(menu.getUrl(),url)){
//            if(menu.getUrl().equals(url)){
                String[] roles = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(roles);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
